import axios from 'axios'
import { ElMessage } from 'element-plus'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = getToken()
    console.log('Request Config:', config);
    console.log('Token:', token);
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    console.log('Final Headers:', config.headers);
    return config
  },
  error => {
    console.error('Request Error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    console.log('Response Data:', response.data);
    // 检查后端返回的数据结构
    const res = response.data;
    
    // 如果后端返回的数据中包含code字段，说明是标准响应格式
    if (res.code !== undefined) {
      if (res.code === 200) {
        return res;
      } else {
        // 处理非成功状态码
        ElMessage({
          message: res.message || '请求失败',
          type: 'error',
          duration: 5 * 1000
        });
        return Promise.reject(new Error(res.message || '请求失败'));
      }
    }
    
    // 如果没有code字段，直接返回数据
    return res;
  },
  error => {
    console.log('Response Error:', error);
    ElMessage({
      message: error.response?.data?.detail || error.message || '请求失败',
      type: 'error',
      duration: 5 * 1000
    });
    return Promise.reject(error);
  }
)

export default service 